package com.xilian.coder.pulltorefreshrecyclerview.footer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;

import com.xilian.coder.pulltorefreshrecyclerview.utils.PullToRefreshRecyclerViewUtil;

/**
 * Created by Administrator on 2017/6/5.
 */

public class BaseLoadMoreView extends RecyclerView.ItemDecoration{
    protected RecyclerView mRecyclerView;
    protected String mLoadMoreString;
    protected static final int MSG_INVILIDATE = 1;
    protected long mUpdateTime = 150;
    protected PullToRefreshRecyclerViewUtil mptrrvUtil;
    protected int mLoadMorePadding = 100;
    protected OnDrawListener mOndrawListener;

    public BaseLoadMoreView(Context context,RecyclerView recyclerView){
        this.mRecyclerView = recyclerView;
        mptrrvUtil = new PullToRefreshRecyclerViewUtil();
    }

    public interface OnDrawListener{
        public boolean onDrawLoadMore(Canvas c,RecyclerView parent);
    }

    public String getLoadMoreString() {
        return mLoadMoreString;
    }

    public void setLoadMoreString(String str) {
        this.mLoadMoreString = str;
    }

    public int getLoadMorePadding() {
        return mLoadMorePadding;
    }

    public void setLoadMorePadding(int padding) {
        this.mLoadMorePadding = padding;
    }

    protected Handler mInvaildateHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(mRecyclerView == null || mRecyclerView.getAdapter() == null){
                return;
            }
            int lastItemPosition = mRecyclerView.getAdapter().getItemCount() - 1;
            if(mptrrvUtil.findLastVisibleItemPosition(mRecyclerView.getLayoutManager()) == lastItemPosition){
                mRecyclerView.invalidate();
            }
        }
    };

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDrawOver(c, parent, state);
        mInvaildateHandler.removeMessages(MSG_INVILIDATE);
        onDrawLoadMore(c,parent);
        mInvaildateHandler.sendEmptyMessageDelayed(MSG_INVILIDATE,mUpdateTime);
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if(itemPosition == parent.getAdapter().getItemCount() - 1){
            outRect.set(0,0,0,getLoadMorePadding());
        }
    }

    protected void onDrawLoadMore(Canvas c,RecyclerView parent){
        if(mOndrawListener != null){
            if(mOndrawListener.onDrawLoadMore(c,parent)){
                return;
            }
        }
    }

    public void setOnDrawListener(OnDrawListener listener){
        this.mOndrawListener = listener;
    }

    public void release(){
        this.mRecyclerView = null;
    }
}
